import { useRef, useState } from 'react';
import { Button, Space, Form, Row, Col, Input, Spin, Popover, Card, Pagination } from 'antd';
import type { QueryStationMonitorListParams } from './services';
import { queryStationMonitorList } from './services'
import { useRequest } from 'ahooks';
import { queryTerminalStatus } from '@/pages/home/service';
import { Access, styled } from '@umijs/max'
import { QuestionCircleOutlined, RightOutlined } from '@ant-design/icons';
import { queryStationListForSelectOption } from '../stationList/services';
import { history } from '@umijs/max'
import { GunStatus, GunStatusColorMap } from '../stubList/services';
import { jump2target } from '@/utils/common';

const StubRow = styled.div`
  width: 100%;
  display: flex;

  .item {
    width: 180px;
    height: 64px;
    padding: 0 24px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    border-right: 1px solid #eeeeee;

    &:last-child {
      border-right: 0;
    }

    .header {
      display: flex;
      justify-content: space-between;
      font-size: 14px;
      color: #888888;

      .extra {
        color: orange;
        cursor: pointer;
      }
    }

    .value {
      font-size: 28px;
      line-height: 28px;
      font-weight: bold;
    }
  }
`

const Statistics = styled.div`
  width: 100%;
  display: grid;
  grid-template-columns: repeat(6, 1fr);

  .item {
    width: 100%;
    height: 54px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-between;

    .title {
      font-size: 14px;
      color: #888888;
    }

    .value {
      font-size: 28px;
      line-height: 28px;
      font-weight: bold;
    }
  }
`

type StubItem = {
  title: string
  explain?: string
  extra?: {
    label: string
    url: string
  },
  value: number
}

const AppUserPage: React.FC = () => {
  const [searchForm] = Form.useForm()
  const [searchParams, setSearchParams] = useState<QueryStationMonitorListParams>({
    pageNum: 1, pageSize: 12, 
  })
  const list = useRequest(() => queryStationMonitorList(searchParams), {
    refreshDeps: [searchParams],
  })
  const stationList = useRequest(queryStationListForSelectOption)
  const stubItems = useRef<StubItem[]>([
    {title: '全部', value: 0},
    {title: '故障', extra: {label: '详情', url: '/fault/stubFault'}, value: 0},
    // {title: '离线', extra: {label: '详情', url: '/station/stubLog'}, value: 0},
    {title: '离线', value: 0},
    {title: '占用', explain: '充电后插枪占位', value: 0},
    {title: '充电中', value: 0},
    {title: '空闲', value: 0},
    {title: '其他', value: 0},
  ])
  const stubCount = useRequest(queryTerminalStatus, {
    onSuccess: (_data) => {
      const { data } = _data
      stubItems.current[1].value = data.acErrorNum + data.dcErrorNum
      stubItems.current[2].value = data.acOffLineNum + data.dcOffLineNum
      stubItems.current[3].value = data.acOccupyNum + data.dcOccupyNum
      stubItems.current[4].value = data.acChargeNum + data.dcChargeNum
      stubItems.current[5].value = data.acFreeNum + data.dcFreeNum
      stubItems.current[6].value = data.acOtherNum + data.dcOtherNum
      stubItems.current[0].value = stubItems.current[1].value + stubItems.current[2].value + 
                                   stubItems.current[3].value + stubItems.current[4].value + 
                                   stubItems.current[5].value + stubItems.current[6].value
    }
  })

  const onFinish = (formValues: any) => {
    setSearchParams({
      ...searchParams,
      stationKeyword: formValues.stationKeyword,
      pageNum: 1,
    })
  }

  const jump2detail = (url: string) => {
    jump2target(url, {needRefresh: true})
  }

  const jump2stationDetail = (id: string) => {
    jump2target(`/station/watch/detail?id=${id}`, {needRefresh: true})
  }
  
  return (
    <div className='container'>
      <div className="card">
        <div className="header">
          <div style={{display: 'flex', alignItems: 'center', gap: 8}}>
            <span>平台场站-监控汇总</span>
            <span style={{fontSize: 14, color: '#888888', fontWeight: 400}}>共{stationList.data?.data.length || 0}个电站实时监控中</span>
          </div>
        </div>
        <Spin spinning={stubCount.loading}>
          <StubRow>
            {
              stubItems.current.map(item => (
                <div className="item" key={item.title}>
                  <div className="header">
                    <Space>
                      <span>{item.title}</span>
                      <Access accessible={!!item.explain}>
                        <Popover content={item.explain}>
                          <QuestionCircleOutlined />
                        </Popover>
                      </Access>
                    </Space>
                    <Access accessible={!!item.extra}>
                      <span className="extra" onClick={() => jump2detail(item.extra!.url)}>
                        {item.extra?.label}
                        <RightOutlined />
                      </span>
                    </Access>
                  </div>
                  <div className="value">{item.value}</div>
                </div>
              ))
            }
          </StubRow>
        </Spin>
      </div>
      <div className="card search-card">
        <div className="form-area">
          <Form
            name='searchWatchForm' form={searchForm} 
            onFinish={onFinish}
          >
            <Row gutter={[20, 20]}>
              <Col span={6}>
                <Form.Item label='场站名称' name='stationKeyword'>
                  <Input placeholder='请输入' />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Space>
                  <Button type='primary' htmlType='submit' loading={list.loading}>筛选</Button>
                  <Button htmlType='reset'>重置</Button>
                </Space>
              </Col>
            </Row>
          </Form>
        </div>
      </div>
      <div className="card content-card">
        <div className="header">单站监控</div>
        <Spin spinning={list.loading}>
          <Row gutter={[16, 16]}>
            {
              list.data?.data.map(item => {
                return <Col span={8} key={item.id}>
                  <Card
                    title={<span style={{color: '#444444'}}>{item.name}</span>}
                    extra={<Space style={{cursor: 'pointer'}} onClick={() => jump2stationDetail(item.id)}>
                      <span style={{color: '#888888'}}>详情</span>
                      <RightOutlined style={{color: '#888888'}} />
                    </Space>}
                  >
                    <Statistics>
                      <div className="item">
                        <div className="title">故障</div>
                        <div className="value" style={item.warning ? {color: GunStatusColorMap[GunStatus.故障]} : {color: '#444444'}}>{item.warning}</div>
                      </div>
                      <div className="item">
                        <div className="title">离线</div>
                        <div className="value" style={item.outline ? {color: GunStatusColorMap[GunStatus.离线]} : {color: '#444444'}}>{item.outline}</div>
                      </div>
                      <div className="item">
                        <div className="title">占用</div>
                        <div className="value" style={item.using ? {color: GunStatusColorMap[GunStatus.充电后占位]} : {color: '#444444'}}>{item.using}</div>
                      </div>
                      <div className="item">
                        <div className="title">充电中</div>
                        <div className="value" style={item.charging ? {color: GunStatusColorMap[GunStatus.充电中]} : {color: '#444444'}}>{item.charging}</div>
                      </div>
                      <div className="item">
                        <div className="title">空闲</div>
                        <div className="value" style={item.free ? {color: GunStatusColorMap[GunStatus.空闲]} : {color: '#444444'}}>{item.free}</div>
                      </div>
                      <div className="item">
                        <div className="title">其他</div>
                        <div className="value" style={item.other ? {color: GunStatusColorMap[GunStatus.其他]} : {color: '#444444'}}>{item.other}</div>
                      </div>
                    </Statistics>
                  </Card>
                </Col>
              })
            }
          </Row>
        </Spin>
        <Pagination
          style={{textAlign: 'right'}}
          showQuickJumper
          current={searchParams.pageNum}
          pageSize={searchParams.pageSize}
          pageSizeOptions={[12, 24, 48, 96]}
          total={list.data?.totalCount || 0}
          onChange={(page, pageSize) => {
            if (page === searchParams.pageNum) {
              setSearchParams({...searchParams, pageNum: 1, pageSize})
            } else {
              setSearchParams({...searchParams, pageNum: page})
            }
          }}
        />
      </div>
    </div>
  );
};

export default AppUserPage;
